const express = require('express');
const fs = require('fs');
const path = require('path');
const cors = require('cors');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const mysql = require('mysql2/promise');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const multer = require('multer');
const ftp = require('basic-ftp');

const app = express();
const PORT = process.env.PORT || 3000;

// ======= 中间件 =======
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(cookieParser());

// ======= JWT 密钥 =======
const JWT_SECRET = process.env.JWT_SECRET || 'a_very_secure_and_long_jwt_secret_key_123456!@#';

// ======= 视频目录处理 =======
const VIDEO_DIR = path.join(__dirname, 'videos');
if (!fs.existsSync(VIDEO_DIR)) {
    fs.mkdirSync(VIDEO_DIR);
    console.log(`已创建视频目录：${VIDEO_DIR}`);
}

// ======= MySQL 数据库配置 =======
const dbConfig = {
    host: '127.0.0.1',
    user: 'root',
    password: '42576138',
    database: 'lab3',
    port: 3306
};
const pool = mysql.createPool(dbConfig);

async function initializeDatabase() {
    try {
        const connection = await pool.getConnection();
        await connection.query(`
            CREATE TABLE IF NOT EXISTS users (
                id INT AUTO_INCREMENT PRIMARY KEY,
                account VARCHAR(255) NOT NULL UNIQUE,
                email VARCHAR(255) NOT NULL,
                password VARCHAR(255) NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        `);
        connection.release();
        console.log('数据库表已初始化');
    } catch (error) {
        console.error('数据库初始化失败:', error);
    }
}
initializeDatabase();

// ======= 用户注册 =======
app.post('/api/register', async (req, res) => {
    try {
        const { account, email, password } = req.body;
        if (!account || !email || !password) {
            return res.status(400).json({ success: false, message: '所有字段都是必填的' });
        }

        const [existingUsers] = await pool.query('SELECT * FROM users WHERE account = ?', [account]);
        if (existingUsers.length > 0) {
            return res.status(400).json({ success: false, message: '账号已存在' });
        }

        const hashedPassword = bcrypt.hashSync(password, 8);
        await pool.query('INSERT INTO users (account, email, password) VALUES (?, ?, ?)', [account, email, hashedPassword]);

        res.json({ success: true, message: '注册成功' });
    } catch (error) {
        console.error('注册错误:', error);
        res.status(500).json({ success: false, message: '服务器错误' });
    }
});

// ======= 用户登录 =======
app.post('/api/login', async (req, res) => {
    try {
        const { account, password, rememberMe } = req.body;
        if (!account || !password) {
            return res.status(400).json({ success: false, message: '账号和密码不能为空' });
        }

        const [rows] = await pool.query('SELECT * FROM users WHERE account = ?', [account]);
        if (rows.length === 0) {
            return res.status(401).json({ success: false, message: '用户不存在' });
        }

        const user = rows[0];
        const passwordMatch = bcrypt.compareSync(password, user.password);
        if (!passwordMatch) {
            return res.status(401).json({ success: false, message: '账号或密码错误' });
        }

        const token = jwt.sign(
            { id: user.id, account: user.account },
            JWT_SECRET,
            { expiresIn: rememberMe ? '30d' : '1h' }
        );

        res.json({
            success: true,
            token,
            user: {
                id: user.id,
                account: user.account,
                email: user.email
            }
        });
    } catch (error) {
        console.error('登录错误:', error);
        res.status(500).json({ success: false, message: '服务器错误' });
    }
});

// ======= 视频上传处理 =======
const upload = multer({ dest: 'temp_uploads/' });
app.post('/upload', upload.single('video'), async (req, res) => {
    if (!req.file) return res.status(400).json({ success: false, message: '未上传文件' });

    const originalName = req.file.originalname;
    const tempPath = req.file.path;
    const targetPath = path.join(VIDEO_DIR, originalName);

    try {
        fs.renameSync(tempPath, targetPath);

        // FTP 上传
        const client = new ftp.Client();
        await client.access({
            host: 'www.doinm.top',
            port: 21, // 改为你的端口，默认 FTP 为 21
            user: '18228869733',
            password: '42576138Hf@#',
            secure: false
        });

        await client.ensureDir('/videos');
        await client.uploadFrom(targetPath, `/videos/${originalName}`);
        client.close();

        res.json({ success: true, message: '上传成功并同步至 FTP' });
    } catch (err) {
        console.error('上传错误:', err);
        res.status(500).json({ success: false, message: '上传失败', error: err.message });
    }
});

// ======= 视频列表 =======
app.get('/videos', (req, res) => {
    fs.readdir(VIDEO_DIR, (err, files) => {
        if (err) {
            console.error('读取目录错误:', err);
            return res.status(500).json({ error: '读取失败' });
        }

        const videos = files
            .filter(file => ['.mp4', '.webm', '.ogg'].includes(path.extname(file).toLowerCase()))
            .map(file => ({
                title: path.basename(file, path.extname(file)),
                path: file,
                type: `video/${path.extname(file).slice(1)}`
            }));

        res.json(videos);
    });
});

// ======= 视频播放 =======
app.get('/video/:filename', (req, res) => {
    const filename = decodeURIComponent(req.params.filename);
    const filePath = path.join(VIDEO_DIR, filename);

    if (!fs.existsSync(filePath)) return res.status(404).send('视频文件未找到');

    const stat = fs.statSync(filePath);
    const fileSize = stat.size;
    const range = req.headers.range;

    if (range) {
        const parts = range.replace(/bytes=/, "").split("-");
        const start = parseInt(parts[0], 10);
        const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
        const chunksize = end - start + 1;

        const file = fs.createReadStream(filePath, { start, end });
        const head = {
            'Content-Range': `bytes ${start}-${end}/${fileSize}`,
            'Accept-Ranges': 'bytes',
            'Content-Length': chunksize,
            'Content-Type': 'video/mp4',
        };

        res.writeHead(206, head);
        file.pipe(res);
    } else {
        const head = {
            'Content-Length': fileSize,
            'Content-Type': 'video/mp4',
        };
        res.writeHead(200, head);
        fs.createReadStream(filePath).pipe(res);
    }
});

// ======= 页面路由 =======
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'login.html'));
});

app.get('/player', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'video_player.html'));
});

// ======= 启动服务器 =======
app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
    console.log(`请将视频文件放入 ${VIDEO_DIR} 目录中`);
});
